let mysql = require('mysql')

let pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'haier'
})

function doSql(sql, params = []) {
    return new Promise((resolve, reject) => {
        pool.getConnection(function (err, connection) {
            if (err) {
                reject(err)
                return;
            }
            connection.query(sql, params, function (error, results, fields) {
                //将链接返回到连接池中，准备由其他人重复使用
                connection.release();
                if (error) {
                    reject(error)
                }
                resolve(results)
            });
        });
    })
}

function hand(data, total) {
    return JSON.stringify({
        success: true,
        code: 20000,
        errorCode: 0,
        msg: '数据请求成功',
        data: data,
        total: total
    })
}

function getData(data) {
    return JSON.stringify({
        success: true,
        code: 20000,
        errorCode: 0,
        msg: '数据请求成功',
        data: data
    })
}

function addData(data) {
    return JSON.stringify({
        success: true,
        code: 20000,
        errorCode: 0,
        msg: '数据新增成功',
        data: data
    })
}

function updateData(data) {
    return JSON.stringify({
        success: true,
        code: 20000,
        errorCode: 0,
        msg: '数据修改成功',
        data: data
    })
}

function deleteData(data) {
    return JSON.stringify({
        success: true,
        code: 20000,
        errorCode: 0,
        msg: '数据删除成功',
        data: data
    })
}

function handleNoResults(){
    return JSON.stringify({
        success: false,
        code: 20000,
        errorCode: 0,
        msg: '数据请求失败'
    })
}

exports.doSql = doSql
exports.getData = getData
exports.addData = addData
exports.updateData = updateData
exports.deleteData = deleteData
exports.hand = hand
exports.handleNoResults = handleNoResults